var key_num=-10;
var omyMusic=document.getElementById("myMusic");
var UI = {

	choiceEmojl : function(key) {
		// var emojiHtml = "<img data-alias='hehe' src='" + _emojl[key] + "' width='25' height='25' title='"+key+"'/>";
		// myFn.parseContent();
		$("#messageBody").val($("#messageBody").val() +key);
		$("#emojl-panel #gifList").getNiceScroll().hide();//隐藏滚动条
		$("#emojl-panel #emojiList").getNiceScroll().hide();
		$("#emojl-panel").hide();
	},
	// 提醒用户打开通知
	noticeUserOpen:function(){
		if(null!=ConversationManager.notice){
			return;
		}else{
			ConversationManager.notice="requesting"
			Notification.requestPermission(function(status) {
				ConversationManager.notice=status;

            });
		}

	},
	//显示通知
	showNotification:function (url,name,body){
        if(!window.Notification) {
           return;
        }
       if(ConversationManager.notice=="granted"){
        	var notification=new Notification(name+":",{
	                        body : body, //显示内容
	                        //以下是可选参数
	                        icon :url,
	                        silent:true,
	                        renotify:true,

	                         tag:"imWeb",
	                        //lang :
	                        onclick:function(){
	                        	this.close();
	                        }


	                    });
        }

    },
    // 播放消息提醒声音
	playSound:function(){
		var omyMusic=document.getElementById("myMusic");
		 omyMusic.play();//播放音乐
	},
	online:function(){
		// 用户在线
		$("#myAvatar").removeClass("headChang");
		$("#user_online").removeClass("user_online");
		$("#user_online").addClass("user_back");
	},
	offline:function(){
		// 用户离线
		$("#myAvatar").addClass("headChang");
		$("#user_online").removeClass("user_back");
		$("#user_online").addClass("user_online");
	},
	createItem : function(msg, fromUserId, direction,isSend) {   //消息Item
		//direction  1 自己发送的   0 别人发送的
		//isSend  发送后创建消息
		//shikuLog(" createItem msg => "+ JSON.stringify(msg));
		if (1!=ConversationManager.isGroup) {
			if (myData.userId!=msg.fromUserId) {
				var friend =DataMap.friends[msg.fromUserId];
				if(!myFn.isNil(friend)){
					if(friend.remarkName)
						msg.fromUserName=friend.remarkName;
					else if(!msg.fromUserName)
						msg.fromUserName=friend.toNickname;
				}
			}

		} else {
			if(myData.userId!=msg.fromUserId)
				DataUtils.getGroupMsgFromUserName(msg,msg.fromUserId);

		}

		var contentHtml = this.createMsgContent(msg,direction,isSend);
		var html="";

		if(myFn.isNil(contentHtml))
			return "";
		var imgUrl=msg.imgUrl;
		//用户头像
		if(myFn.isNil(msg.imgUrl)){
			imgUrl=myFn.getAvatarUrl(WEBIM.CHAT==msg.chatType?fromUserId:msg.fromUserId);
		}
		var delayTime=msg.timeSend-DataMap.timeSendLogMap[ConversationManager.fromUserId];

		var timeSendStr = "";
		//||delayTime< -(60*10)
		if(delayTime>(60*10)||delayTime< -(60*10)){
				// var timeSendHtml=UI.createTimeSendLog(msg.timeSend);
				// html+=timeSendHtml;
				DataMap.timeSendLogMap[ConversationManager.fromUserId]=msg.timeSend;
				timeSendStr = getTimeText(msg.timeSend,0,1);
		}


		html+= "<div id=msg_"+msg.messageId+" msgType="+msg.type+" class='msgDiv' >"
            +		"<div class='clearfix'>"
			+			"<div style='overflow: hidden;' >"
			+	    		"<div  class='message " + (0 == direction ? "you" : "me")+"'>"
			+			        "<div  class='message_system'>"
			+			        	"<div  class='content'>"+timeSendStr+"</div>"
			+			        "</div>"
			+	        		"<img  class='"+ (1==ConversationManager.isGroup && 0==direction ? " group_avatar":" avatar") + "' onerror='this.src=\"../img/ic_avatar.png\"' src='" +imgUrl+ "' >"
			+	        		"<div class='content'>"
			+       (0==direction ? "<h4  class='nickname'> 客服" + msg.fromUserName + "</h4>" : "")
								//msg type = 5 表示 gif 动态图 ，若为gif消息则不添加消息气泡背景
            +	            	"<div class='bubble js_message_bubble  "+ (0 == direction ?(5 == msg.type?"left'>":"bubble_default left'>"):(5 == msg.type?"right'>":"bubble_primary right'>"))
			+	               		 "<div class='bubble_cont'>"
			+                          contentHtml
			+	               		 "</div>"
			+	            	"</div>"
			+	        	"</div>"
			+	    	"</div>"
			+		"</div>"
			+	"</div>"
       		+"</div>";


		return html;

	},
	/*type 为1  的文本消息*/
	createTextMsgContent:function(msg,direction,isSend,contentHtml,msgStatusHtml){
		var content = "";
		content=myFn.parseContent(msg.content,2);

		contentHtml += "<div class='plain' length='"+msg.content.length+"' >";
		if(!WEBIM.isGroupChat(ConversationManager.chatType)&& 0==direction&&myFn.isReadDelMsg(msg)){
			contentHtml+= "<pre class='js_message_plain hide'>"+ content +"</pre>"
					   +  "<a href='javascript:void(0)' onclick='UI.showReadDelMsg(\""+msg.messageId+"\");' style=''> 点击查看  T</a>"
					   +  "<span id='msgReadTime_"+msg.messageId+"' class='msg_status_common read_del_time'>10</span>"
					   +"</div>";

			if(1==msg.isShow){
				setTimeout(function(){
					UI.showReadDelMsg(msg.id);
				},1000);
			}
		}else{
			contentHtml += "<pre class='js_message_plain'>"+ content +"</pre>"
								   + msgStatusHtml
								   + "</div";
		}
		return contentHtml;
	},
	createMsgContent:function(msg,direction,isSend){

			var contentHtml = "";

			if(myFn.isNil(msg.content)){
				return null;
			}
			msg.content=(msg.content+"").replaceAll('\n','<br/>');

			var msgStatusHtml  ="";  this.createMsgStatusIteam(msg,direction,isSend);
			if(99<msg.type&&125>msg.type){
				contentHtml=this.createTextMsgContent(msg,direction,isSend,contentHtml,msgStatusHtml);
				return contentHtml;
			}
			   msgStatusHtml=this.createMsgStatusIteam(msg,direction,isSend);
			switch (msg.type){

				case 1:// 文字、表情

					contentHtml=this.createTextMsgContent(msg,direction,isSend,contentHtml,msgStatusHtml);

				  break;

				case 2:// 图片

                   	contentHtml +=  '<div class="picture">';
				 	if("true"==msg.isReadDel ||1==msg.isReadDel){ //判断是否为阅后即焚消息
				 		contentHtml += '<img id="readDelImg" class="shade" src="' + msg.content + '" style="max-width:320px;max-height:320px;"  onclick="UI.showImgZoom(\'' + msg.content + '\',\''+msg.messageId+'\')"/>';
				 	}else{ //不是
				 		contentHtml += '<img class="msg-img" onerror="this.src=\'../img/overdue.png\'" src="' + msg.content + '" onclick="UI.showImgZoom(\'' + msg.content + '\')">';
				 	}

                    contentHtml += '</div>'
				 				+msgStatusHtml;

				  break;

				case 3:// 语音

					if("groupchat"==msg.chatType && myData.isShowGroupMsgReadNum){
						contentHtml = "<p id='voiceP_"+msg.id+"' class='chat_content' onclick='UI.showAudio(\"" + msg.content + "\",\"" + msg.id + "\",\""+msg.isReadDel+"\");GroupManager.sendRead(\"" + msg.id + "\")'>"
								+     "<img id='voiceImg' src='../img/voice.png' style='width:25px; height:25px;margin-top:-2.5px'> <span style='display:inline; margin-left:15px; margin-right:10px;'>"+msg.timeLen+"\" </span>"
								+	  "<div id='voice_"+msg.id+"'></div>"
								+ "</p>"
								+msgStatusHtml;
					}else{
						contentHtml = "<p id='voiceP_"+msg.id+"' class='chat_content' onclick='UI.showAudio(\"" + msg.content + "\",\"" + msg.id + "\",\""+msg.isReadDel+"\")'>"
								+     "<img id='voiceImg' src='../img/voice.png' style='width:25px; height:25px;margin-top:-2.5px'> <span style='display:inline; margin-left:15px; margin-right:10px;'>"+msg.timeLen+"\" </span>"
								+	  "<div id='voice_"+msg.id+"'></div>"
								+ "</p>"
								+msgStatusHtml;
					}

				  break;

				case 4:// 位置


 					contentHtml = '<div class="location">'
 								+	'<a href="javascript:void(0)" onclick="showToMap(this)"'+' lng="'+msg.location_x+' "lat="'+msg.location_y+'">'
 								+		'<img alt="" class="img" src="'+BaiduMap.imgApiUrl+msg.location_y+','+msg.location_x+' ">'
 								+		'<p class="desc ng-binding">'+msg.objectId+'</p>'
 								+	'</a>'
 								+ '</div>'
 								+ msgStatusHtml;
     				break;


				case 5:// GIF 动画

					contentHtml = '<div class="emoticon">'
			                	+	'<img  class="custom_emoji msg-img"  src="../gif/'+ msg.content +'">'
			            		+ '</div>'
			            		+ msgStatusHtml;

				   break;

				case 6:// 视频
					if("groupchat"==msg.chatType && myData.isShowGroupMsgReadNum){
								contentHtml =	"<video class='video' controls  onended='UI.videoPlayEnd(\"" + msg.id + "\",\""+msg.isReadDel+"\")' style='width:240px;height:240px;'>"
							  	+			"<source src='"+msg.content+"' type='video/mp4'>"
								+		"</video>"
								+		"<script>plyr.setup();</script>";
					}else{
								contentHtml = 	"<video style='width:240px;margin-top:1%;border-radius:5px' class='video' controls onplay='GroupManager.sendRead(\"" + msg.id + "\")'  onended='UI.videoPlayEnd(\"" + msg.id + "\",\""+msg.isReadDel+"\")' >"
							  	+			"<source src='"+msg.content+"' type='video/mp4'>"
								+		"</video>"
								+		"<script>plyr.setup();</script>"
					}

				  break;
				case 7:// 音频

				  break;

				case 8: // 名片

					contentHtml =	'<div class="card" onclick="UI.showUser(\''+ msg.objectId + '\')">'
				                +        '<div class="card_bd">'
				                +            '<div class="card_avatar">'
				                +                '<img class="img"  onerror=\'this.src=\"../img/ic_avatar.png\"\' src=\'' + myFn.getAvatarUrl(msg.objectId) + '\' >'
				                +            '</div>'
				               	+            '<div class="info">'
				                +                '<h3 class="display_name">'+ msg.content +'</h3>'
				                +            '</div>'
				                +        '</div>'
				                +        '<div class="card_hd">'
				                +        	'<p class="">个人名片</p>'
				                +        '</div>'
				                +    '</div>'
								+ msgStatusHtml;
				  	break;

				case 9:// 文件
					var fileStr="";
					var fileName="";
					if(!myFn.isNil(msg.fileName)){
						fileStr=msg.fileName.substring(msg.fileName.lastIndexOf("/")+1);
						fileName=fileStr.substring(0,fileStr.indexOf("."));
					}else{
						fileStr=msg.content.substring(msg.content.lastIndexOf("/")+1);
						fileName=fileStr.substring(0,fileStr.indexOf("."));
					}
					contentHtml = '<div class="bubble_cont primary">'
								+		'<div class="attach">'
				                +        	'<div class="attach_bd">'
				                +            	'<div class="cover">'
				                +                	'<i class="icon_file"></i>'
				                +           	'</div>'
				                +            	'<div class="cont">'
				                +                	'<p class="title">'+fileStr+'</p>'
				                +                	'<div class="opr">'
				                +                    	'<span  class="">'+myFn.parseFileSize(msg.fileSize)+'</span>'
				                +                    	'<span class="sep">  |  </span>'
				                +                   	'<a target="_blank" id="fileDown_'+msg.messageId+'" download="'+fileName+'"  filename="'+fileName+'"  href="' + msg.content+ '"  class="">下载</a>';
				   	if(1 == direction && 1==isSend ){
					    contentHtml +=						'<p id="fileProgress_'+msg.messageId+'" class="progress_bar">'
					            	+                            '<span class="progress" style="width: 0%;"></span>'
					                +                       '</p>';
					}
				     contentHtml+=                	'</div>'
				                +            	'</div>'
				                +        	'</div>'
				                +    	'</div>'
								+ '</div>'
								+ msgStatusHtml;

				  	break;
				case 10://提醒
				 	UI.showMsgLog(msg.content,msg.messageId);
				 	return;
				  break;
				case 26:// 已读回执
					DataMap.msgStatus[msg.content]  =  2; //将发送消息状态进行储存 2:已读
			 		var message = DataUtils.getMessage(msg.content);
			 		if(myFn.isNil(message))
			 			return;
			 		if(0 == direction&&myFn.isReadDelMsg(message)){
			 			if(1==msg.isRead)
			 				return;
			 			DataUtils.deleteMessage(msg.content);
			 			if(1 == message.type||2 == message.type||3 == message.type||
			 				6 == message.type){
			 				$("#msg_"+msg.content+"").remove();
			 				if(msg.fromUserId==ConversationManager.fromUserId){
			 					UI.refreshLastMsgtoMessageList();
			 					UI.showMsgLog("对方查看了你的这条阅后即焚消息");

			 				}
			 				return ;
			 			}

			 		}
			 		if(myFn.isReadDelMsg(message))
			 			DataUtils.deleteMessage(msg.content);
			 		$("#msgStu_"+msg.content+"").css("background-color" ,"#7BD286");
			 		$("#msgStu_"+msg.content+"").text("已读").show();
			 		return;
				  break;
				case 28://红包
					contentHtml = '<div onclick="UI.openRedPacket(\''+msg.objectId+'\')" class="" style="background:#ff8a2a;">'
								+		'<div class="attach" style="background:#ff8a2a;padding-top:4px">'
				                +        	'<div class="attach_bd">'
				                +            	'<div class="cover">'
				                +                	'<img src="../img/ic_chat_hongbao.png">'
				                +           	'</div>'
				                +            	'<div class="cont" style="line-height:60px;">'
				                +               '<p style="color:white">'+(msg.fileName==3?"口令: ":"")+msg.content+'</p>'
				                +            	'</div>'
				                +        	'</div>'
				                +    	'</div>'
								+ '</div>'
								+ msgStatusHtml;
					break;


				  break;
				case 501://同意加好友
					UI.showMsgLog(msg.content);
					UI.showNewFriends(0);
				  break;
				case 201:// 正在输入
					// ownAlert(3,"正在输入");
					$("#chatHint").empty().text("对方正在输入......");
				 	$("#chatHint").show();
					setTimeout(function () {  //过5秒后隐藏
						$("#chatHint").empty();
		        		$("#chatHint").hide();
		    		}, 5000);
					return;
				  break;
				case 80://单条图文

				  break;
				case 81://多条图文

				  break;
				case 202://消息撤回
					//msg.messageId=msg.content;
					var recallHtml = "";
					if(msg.fromUserId==myData.userId){ //我自己
						recallHtml = "<div class='logContent'><span>你撤回了一条消息 ("+myFn.toDateTime(msg.timeSend)+")</span></div>";
					}else{
						recallHtml = "<div class='logContent'><span>"+msg.fromUserName+" 撤回了一条消息 ("+myFn.toDateTime(msg.timeSend)+")</span></div>";
					}


					$("#messageContainer #msg_"+msg.msgId).remove();
					$("#messageContainer").append(recallHtml);

				 	return;
				  break;

				default://默认 其他
				contentHtml+="<p class='plain'>";
							contentHtml+= "[web不支持 请在手机上查看]</p>";

			}
			if(1==ConversationManager.isGroup&&msg.type>400){
				WEBIM.converGroupMsg(msg);
				UI.showMsgLog(msg.content);
				 	return;
			}
			return contentHtml;
	},
	//生成消息状态标签 (包括：loading  送达 已读  失败重发 阅后即焚计时 群已读人数等)
	createMsgStatusIteam:function(msg,direction,isSend){

		var  msgStatusHtml = "";

		//单聊消息
		if(1!=ConversationManager.isGroup) {
				//0 == direction  表示接受到的消息       1 == direction  表示用户自己发送的消息
				msgStatusHtml += ( 0 == direction ? "" : 1==isSend ? "<span id='msgStu_"+msg.messageId+"'  class='msg_status_common send_status'></span>"
					+"<img id='msgLoad_"+msg.messageId+"' class='msg_status_common ico_loading' src='../img/loading.gif'>" :
					(true == msg.isRead ?"<span class='msg_status_common send_status read_bg'>已读</span>" :
						(1 == msg.isReadDel ? "<img class='msg_status_readDel ico_readDel' src='../img/fire.png'><span  id='msgStu_"+msg.messageId+"' class='msg_status_readDel send_status ok_bg'>送达</span>" :
							"<span  id='msgStu_"+msg.messageId+"'  class='msg_status_common send_status ok_bg' style=''>送达</span>")) );


		}
		return  msgStatusHtml;
	},
	//发送消息
	sendMsg : function(msg,toJid) {


		msg.id=msg.messageId;

		var jid=null;
		if(myFn.isNil(toJid))
			jid=ConversationManager.fromUserId;
		else
			jid=WEBIM.getUserIdFromJid(toJid);

		if(!WEBIM.isGroup(jid)){
			UI.processSendMsg(msg,toJid);
			return;
		}
		var talkTime=DataMap.talkTime[jid];
		if(myFn.isNil(talkTime)||0==talkTime){
			UI.processSendMsg(msg,toJid);
			return;
		}else if(0!=GroupManager.roomData.talkTime&&3!=GroupManager.roomData.member.role){
			UI.processSendMsg(msg,toJid);
			return;
		}
		mySdk.getCurrentTime(function(time){
			if(talkTime>time){
				 var date = new Date(ConversationManager.talkTime* 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
			      var  Y = date.getFullYear() + '-';
			      var  M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
			      var  D = date.getDate() + ' ';
			      var  h = date.getHours() + ':';
			      var  m = date.getMinutes() + ':';
			      var  s = date.getSeconds();
				ownAlert(2,Y+M+D+h+m+s+"之前,您被禁止发言");
				return ;
			}else if(time<GroupManager.roomData.talkTime){
				ownAlert(3,"全员禁言中不能发送消息");
				return;
			}
			UI.processSendMsg(msg,toJid);
		});
	},
	//处理发送消息
	processSendMsg:function(msg,toJid){
		var content=msg.content;

		ConversationManager.sendMsg(msg,function(){
			//接受方 为当前打开界面目标用户 才添加消息到界面
			//if(ConversationManager.from==msg.toJid){
				msg.content=content;


				$("#messageBody").val("");
				//其他设备的处理
				if(1!=ConversationManager.isGroup&&myData.userId==msg.toUserId&&1==myData.multipleDevices){
					DeviceManager.processShowMessage(msg,1,0);
				}else{
					if(!(msg.type==2||msg.type==9)){ //图片type=2、文件 type=9 消息上传前已做了UI预加载，这里不再次显示UI
						UI.showMsg(msg,myData.userId,1);
					}
					var isGroup=ConversationManager.isGroup;
					if(toJid){
						isGroup=WEBIM.isGroup(WEBIM.getUserIdFromJid(toJid));
					}else
						isGroup=ConversationManager.isGroup;
						msg.isGroup=isGroup;
						if(300>msg.type)
							UI.moveFriendToTop(msg,msg.toUserId,null,0);
				}
			//}

		},toJid);
	},
	sendImg:function(){
		var imgUrl = $("#myFileUrl").val();
		var arr=new Array();
		arr=imgUrl.split(",");
		for(var i = 0;i<arr.length;i++){
			var msg=WEBIM.createMessage(2, arr[i]);
			UI.sendMsg(msg);
		}
	},
	sendFile:function(){
		var content = $("#myFileUrl").val();
		var arr=new Array();
		arr=content.split(",");
		var arr2=new Array();
		arr2=$("#filePath").val().split(",");
		for(var i=0;i<arr.length;i++){
			var msg=WEBIM.createMessage(9, arr[i]);
			msg.fileName=arr2[i];
			msg.fileSize=$("#filePath").attr("size");
			UI.sendMsg(msg);
		}
	},
	sendGif:function(gifName){
		$("#emojl-panel #gifList").getNiceScroll().hide(); //隐藏滚动条
		$("#emojl-panel").hide();//隐藏表情面板
		var msg = WEBIM.createMessage(5, gifName);
		UI.sendMsg(msg);
	},
	showMsg : function(msg, fromUserId, direction,isSend,isNewMsg) {
		/**
		 * direction  1 自己发送的   0 别人发送的
		 * isSend 是否 显示发送等待符
		 * isNewMsg 是否为新消息  "newMsg"表示新消息
		 */
		if(myFn.isNil(msg.content))
			return;
		if(myFn.isNil(isSend))
			isSend=1;
		else
			isSend=0==isSend?0:1;
		var itemHtml = this.createItem(msg, fromUserId, direction,isSend);
		if(myFn.isNil(itemHtml))
			return "";
		//direction==0  表示收到消息 ，然后根据坐标判断用户是否在查看聊天记录,如果是则在新消息前添加分割标识
		if(isNewMsg =="newMsg" && direction==0  && UI.getElementPos("messageEnd").y > UI.getElementPos("sendMsgScopeDiv").y+300){
			 //在新建分割线之前移除之前的分割线
			 ConversationManager.curViewUnreadNum+=1;
			if (ConversationManager.isShowUnreadCount) { //判断是否需要显示新消息未读统计
				$("#messagePanel").after('<div id="bottomUnreadCount" class="unread-bottom ng-binding" onclick="UI.scrollToBottomUnread()">'+
										'<span class="unread-bottom-icon"></span><span class="unreadNum">1</span> 条新消息</div>');
				ConversationManager.isShowUnreadCount = false;
			}else{
				 $("#bottomUnreadCount .unreadNum").text(ConversationManager.curViewUnreadNum);
			}

			if(ConversationManager.isShowNewMsgCut){
				$("#messageContainer .message_system").remove();
				$("#messageContainer").append('<div class="message_system"><div class="content unread-content">'+
				'<div class="line-left"></div>以下是新消息<div class="line-right"></div></div></div>');
			  	ConversationManager.isShowNewMsgCut = false;
			}

		}
		//将消息显示到界面
		$("#messageContainer").append(itemHtml);
		// 滚动到底部
		setTimeout(function(){
			$(".nano").nanoScroller();//刷新滚动条

			if("newMsg"==isNewMsg){
				UI.scrollToEnd("receive");//滚动到底部
			}else{
				UI.scrollToEnd();
			}
		},500);

	},
	showReSendImg:function(messageId){
		// $("#msgStu_"+id+"").attr("class","msgStatus msgStatusBG"); //改变背景
		if (ConversationManager.isGroup==1) { //群聊

			$("#groupMsgLoad_"+messageId+"").after("<i id='groupMsgResend_"+messageId+"'  class='msg_status_common ico_fail web_wechat_message_fail'  onclick='UI.reSendMsg(\""+messageId+"\")'></i>");
			//移除loading
			$("#groupMsgLoad_"+messageId+"").remove();

		}else{
		 	//消息框显示重发标志
			$("#msgLoad_"+messageId+"").after("<i id='msgResend_"+messageId+"'  class='msg_status_common ico_fail web_wechat_message_fail'  onclick='UI.reSendMsg(\""+messageId+"\")'></i>");
			//移除loading
			$("#msgLoad_"+messageId+"").remove();
		}
	},
	//点击消息重发
	reSendMsg:function(msgId){
		//改变UI
		if(1!=ConversationManager.isGroup){

			$("#msgResend_"+msgId+"").after("<img id='msgLoad_"+msgId+"' class='msg_status_common ico_loading' src='../img/loading.gif'>");
			$("#msgResend_"+msgId+"").remove();
		}else{

			$("#groupMsgResend_"+msgId+"").after("<img id='msgLoad_"+msgId+"' class='msg_status_common ico_loading' src='../img/loading.gif'>");
			$("#groupMsgResend_"+msgId+"").remove();
		}
		//消息重发
		var msg=DataUtils.getMessage(msgId);
		if(myFn.isNil(msg))
			return;
		ConversationManager.sendMsgAfter(msg);
		ConversationManager.sendTimeoutCheck(msgId); //调用方法进行重发检测

	},
	showMsgLog:function(log,messageId){
		var logHtml ="<div class='logContent' >"
						+"	<span >"+log+"</span> "
						+"</div>";
		if(messageId){
			logHtml="<div id='msg_"+messageId+"' >"
			 +logHtml+ "</div>";
		}
		$("#messageContainer").append(logHtml);
		UI.scrollToEnd();
	},
	showTimeSendLog:function(msg){
		var timeSendStr=getTimeText(msg.timeSend,1);
		UI.showMsgLog(timeSendStr);
	},
	showMsgNum :function(userId,isAdd,userIdKey){
		//显示消息数量
		if(!userIdKey)
			userIdKey=userId;
		var msgNum = DataUtils.getMsgNum(userIdKey);
		var messageNumber =DataUtils.getMsgNumCount();
		if(1==isAdd){
			if(myFn.isNil(msgNum)){
				// var i=$("#msgNum_"+userId+"  #span").html();
				// msgNum=parseInt(i);
				msgNum = 1;
			}
			else msgNum+=1;
			DataUtils.setMsgNum(userIdKey,msgNum) ;
			messageNumber += 1; //将好友发送的未读消息汇总
			DataUtils.setMsgMumCount(messageNumber);
		}
		if(0<msgNum){
			if(99<msgNum)
				$("#myMessagesList #msgNum_"+userId+"").html("99+");
			else
				$("#myMessagesList #msgNum_"+userId+"").html(msgNum);
			$("#myMessagesList #msgNum_"+userId).removeClass("msgNumHide");
			$("#myMessagesList #msgNum_"+userId).addClass("msgNumShow");

		}

		// ConversationManager.changMessageNum(0,messageNumber);
		if(0<messageNumber){
			//显示到页面
			if(messageNumber > 99){  //数量大于99 则显示99+
				$("#messages #messageNum").text("99+");
			}else{
				$("#messages #messageNum").text(messageNumber);
			}
			$("#messages #messageNum").removeClass("msgNumHide");
			$("#messages #messageNum").addClass("msgNumShow");
		}

		/*if("NewFriend"==Temp.nowList&&10001==userId)
			UI.showNewFriends(0);*/
	},
	clearMsgNum:function(userId,userIdKey){
		if(!userIdKey)
			userIdKey=userId;
		var msgNum = DataUtils.getMsgNum(userIdKey);
		if(myFn.isNil(msgNum))
			msgNum = 0;
		var messageNumber=DataUtils.getMsgNumCount();
		messageNumber-=msgNum; //将已读的消息数从未读消息汇总数中减去
		DataUtils.setMsgNum(userIdKey,0);
		DataUtils.setMsgMumCount(messageNumber);
		//显示到页面
		if(!messageNumber>0){
			$("#messages #messageNum").removeClass("msgNumShow");
			$("#messages #messageNum").addClass("msgNumHide");
		}else{
			if(messageNumber > 99){  //数量大于99 则显示99+
				$("#messages #messageNum").text("99+");
			}else{
				$("#messages #messageNum").text(messageNumber);
			}
			$("#messages #messageNum").removeClass("msgNumHide");
			$("#messages #messageNum").addClass("msgNumShow");
		}

		$("#myMessagesList #msgNum_"+userId).html(0);

		$("#myMessagesList #msgNum_"+userId).removeClass("msgNumShow");
		$("#myMessagesList #msgNum_"+userId).addClass("msgNumHide");



	},
	showReadDelMsg:function(messageId){
		$("#msg_"+messageId+" a").remove();
		$("#msg_"+messageId+" .js_message_plain").removeClass("hide");
		var length=$("#msg_"+messageId+" .plain").attr("length");
		var timeOut=null;
		var count=0;

		count=parseInt(length)/10;
		count=count<1?10:count*10;
		shikuLog("==========> showReadDelMsg  length > "+length+" count > "+count);

		shikuLog("==========> showReadDelMsg  count > "+count);
		$("#msgReadTime_"+messageId).html(count);

		var msg=DataUtils.getMessage(messageId);
		msg.isShow=1;
		//msg.count=count;
		DataUtils.saveMessage(msg);
		timeOut= setInterval(function(){
			var msg=DataUtils.getMessage(messageId);
			if(msg.fromUserId!=ConversationManager.fromUserId){
				clearInterval(timeOut);
				return;
			}
			count=count-1;
		/*	msg.count=count;
			DataUtils.saveMessage(msg);*/
			if(count>0){
				$("#msgReadTime_"+messageId).html(count);
			}
			else{
				ConversationManager.sendReadReceipt(ConversationManager.from, messageId,1); //发送已读回执

				clearInterval(timeOut);
				$("#msg_"+messageId).remove();
				UI.refreshLastMsgtoMessageList();


			}
		},1000,messageId,timeOut,count);
	},
	showImgZoom : function(src,messageId) {
		$("#imgZoomBody").empty();
		var imgHtml = "<img src='"+src+"' style='max-width: 100%; max-height: 100%;'>";
     	$("#imgZoomModal").modal('show');
     	$("#imgZoomBody").append(imgHtml);
     	if(!myFn.isNil(messageId)){ //阅后即焚消息
     		var msg=DataUtils.getMessage(messageId);
     		if(myData.userId==msg.fromUserId)
     			return;
     		ConversationManager.sendReadReceipt(ConversationManager.from, messageId,1);
     		if(!myFn.isNil(msg))
     			mySdk.deleteFile(msg.content);
			$("#messageContainer #msg_"+messageId).remove();

			//将此条阅后即焚消息从缓存消息中删除
			myFn.deleteReadDelMsg(messageId);
		}

	},
	videoPlayEnd : function(messageId,readDel) { //视频播放结束后执行
		if(readDel=="true" || readDel==1){ //判断是否为阅后即焚消息
			//播放结束后显示阅后即焚图片
			$("#messageContainer #msg_"+messageId+"").remove();
			var msg=DataUtils.getMessage(messageId);
			ConversationManager.sendReadReceipt(ConversationManager.from, messageId,1);
     		if(!myFn.isNil(msg))
     			mySdk.deleteFile(msg.content);
			//将此条阅后即焚消息从缓存消息中删除
			myFn.deleteReadDelMsg(messageId);
		}

	},
	showAudio : function(videoUrl,messageId,readDel) {
		var type=videoUrl.substr(videoUrl.lastIndexOf('.')+1,videoUrl.length);
		if("amr"==type){
			var url=AppConfig.uploadUrl.substr(0,AppConfig.uploadUrl.lastIndexOf('/'))+"/amrToMp3";
			var data=WEBIM.createOpenApiSecret();
			data.paths=videoUrl;

			$.ajax({
				type:"POST",
				url:url,
				jsonp:"callback",
				data:data,
				success : function(result) {
					//if (1 == result.resultCode) {
						var res = eval("(" + result + ")");
						videoUrl=res.data[0].oUrl;
						UI.showAudioInUrl(videoUrl,messageId,readDel);
					//}
				},
				error : function(result) {

				}
			});

		}else if("wav"==type){
			// videoUrl = videoUrl.substr(0, videoUrl.lastIndexOf('.')) + ".mp3";
			UI.showAudioInUrl(videoUrl,messageId,readDel);
		}else{
			videoUrl = videoUrl.substr(0, videoUrl.lastIndexOf('.')) + ".mp3";
			UI.showAudioInUrl(videoUrl,messageId,readDel);
		}
	},
	//根据url 开始播放语音
	showAudioInUrl:function(videoUrl,msgId,readDel){
		//将页面上的语音消息都恢复成静态图片
		$("#messageContainer #voiceImg").attr("src","../img/voice.png");

		//ownAlert(3,"开始播放语音");

		var voiceHtml = '<audio id="audio" autoplay="autoplay">'
					  +		'<source src="'+videoUrl+'" type="audio/mpeg"/>'
					  +'</audio>'
		$("#messageContainer #voice_"+msgId+"").empty().append(voiceHtml);
		//显示播放的gif图
		$("#messageContainer #voiceP_"+msgId+" #voiceImg").attr("src","../img/voice.gif");

		//播放结束后恢复
		$("#messageContainer #voice_"+msgId+" #audio").bind('ended',function () {
			if(readDel=="true" || readDel==1 ){ //判断是否为阅后即焚消息
				$("#messageContainer #msg_"+msgId+"").remove();
				var msg=DataUtils.getMessage(msgId);
     		if(!myFn.isNil(msg))
     			ConversationManager.sendReadReceipt(ConversationManager.from, msgId,1);
     			mySdk.deleteFile(msg.content);
				setTimeout(function(){
					UI.scrollToEnd();
				},400);

				//将此条阅后即焚消息从缓存消息中删除
				myFn.deleteReadDelMsg(msgId);

			}else{ // 不是阅后即焚 则恢复为静态图片
				$("#messageContainer #voiceP_"+msgId+" #voiceImg").attr("src","../img/voice.png");
			}


		});


	},
	deleteMsg:function(type,del,msgId,roomJid,refreshUI,callback){
		//删除消息
		mySdk.deleteMsg(type,del,msgId,function(){
			//上一条消息的Id
			$("#messageContainer #msg_"+msgId).remove();
			if(refreshUI){
				UI.refreshLastMsgtoMessageList();
			}
			if(callback)
				callback();
		},roomJid);
	},
	//滚动到底部  type ：类型分为发送和接收两种
	scrollToEnd : function(type) {

		if(type=="receive" && UI.getElementPos("messageEnd").y> UI.getElementPos("sendMsgScopeDiv").y+300){  //类型为接收
  			//根据坐标判断用户是否在浏览历史消息
		    return;
		}
		$("#bottomUnreadCount").remove();
		//document.getElementById("messageEnd").scrollIntoView();
		$(".nano").nanoScroller({ scrollBottom: -100000000000});
	},
	friendRemarkName(userId){
		Temp.updateNameType="friendRemarkName";
		var friend=DataMap.friends[userId];
		$("#myModalLabel").html("修改好友备注");
		if(!myFn.isNil(friend.remarkName))
			$("#newNickname").val(friend.remarkName);
		else
			$("#newNickname").val("");
		$("#updategname").modal("show");
	},

	nearbyUserClick : function(userId){
		//点击后改变背景
		$("#nearbyUserList #nearUser_"+userId+"").addClass("fActive");
     	$("#nearbyUserList #nearUser_"+userId+"").siblings().removeClass("fActive");
     	UI.showUser(userId);
	},
	showPwd:function() {

		$("#o").hide();
		UI.hideChatBodyAndDetails();
		$("#privacy").hide();
		$("#prop").hide();
		$("#setPassword").show();

	},
	//文件上传
	upload:function(){

		var file= $("#myfile")[0].files[0];

		Temp.file=file;
		var filesize =file.size/1024/1024;
			if(filesize > 20){
                ownAlert(3,"文件大小超过限制，最多20M");
                return false;
            }
            $("#filePath").val(file.name);
            $("#filePath").attr("size",file.size);
           // $("#filePath").after("<img id='loadingimg' src='../img/loading.gif'>");

			$("#uploadFileFrom").ajaxSubmit(function(data) {//成功

				 //$("#uploadFileFrom #icon").hide();
		        var obj = eval("(" + data + ")");
				if (!myFn.isNil(obj.url)) {
					Temp.file.url=obj.url;
					$("#myFileUrl").val(obj.url);
					$("#myfile").val("");
					if(Temp.uploadType=="sendImg"){
						$("#myImgPreview").attr("src",obj.url);
						UI.sendImg();
					} else if("uploadFile"==Temp.uploadType){
						//群文件上传
						GroupManager.addGroupFile(Temp.file);
					}else{
						$("#myFilePreviewPrant #myFilePreview").append(file.name);
						$("#myFilePreviewPrant").show();
						UI.sendFile();
						// ownAlert(3,"上传成功!");
					}


				}
		  });
	},
	//聊天图片上传
	uploadImg:function(){
		layui.upload.render({
		        elem: '#btnImg', //文件选择元素
		        accept:'images',
		        acceptMime: 'image/*',
		        url: AppConfig.uploadUrl+'',
		        size:5000,
		        data:{id:""},
		        progress: function(e , percent) {
		          //console.log("进度：" + percent + '%');
		        },
		        choose: function(obj) {//选择完成事件
		          var imgMsg = Customer.createMessage(2, " ",customerData.serviceId);
		          this.data.id=imgMsg.messageId;

		          obj.preview(function(index, file, result) {

						var reader = new FileReader();
						reader.onload = function(evt){
							imgMsg.content = evt.target.result;
		          			UI.showMsg(imgMsg,myData.userId,1,1,"newMsg");
		          			DataUtils.saveMessage(imgMsg);//储存消息
						}
						reader.readAsDataURL(file);
		          });


		        },
		        done: function(res) { //上传完成事件
					var imgMsg=DataUtils.getMessage(this.data.id);
					imgMsg.content = res.url;
					UI.sendMsg(imgMsg,customerData.serviceId);

		          //UI.sendImg();
		        },
		        error: function(res) {
		          //layui.layer.msg(res.msg);
		        }
		});


	},
	uploadFile:function(){

		layui.upload.render({
		        elem: '#btnFile', //文件选择元素
		        accept:'file',
		        url: AppConfig.uploadUrl+'',
		        data:{id:""},
		        progress: function(e , percent) {
		          //更新进度条
		          document.getElementById('fileProgress_'+this.data.id+'').childNodes[0].style.cssText="width: "+percent+"%;";
		        },
		        choose: function(obj) {//选择完成事件
		          var fileMsg = Customer.createMessage(9, "fileUrl",customerData.serviceId);
		          this.data.id = fileMsg.messageId;
		          obj.preview(function(index, file, result) {
		          		//开始ui预加载
						fileMsg.fileName=file.name;
						fileMsg.fileSize=file.size;
	          			UI.showMsg(fileMsg,myData.userId,1,1,"newMsg");
		           		DataUtils.saveMessage(fileMsg);//储存消息
		          });

		        },
		        done: function(res) { //上传完成事件

		          //移除进度条
		          $("#fileProgress_"+this.data.id+"").remove();
		          //替换下载url
		          $("#fileDown_"+this.data.id+"").attr("href",res.url);
		          //发送消息
		          var fileMsg=DataUtils.getMessage(this.data.id);
				  fileMsg.content = res.url;
				  UI.sendMsg(fileMsg,customerData.serviceId);
		        },
		        error: function(res) {
		          if(res.msg)
		          		layui.layer.msg(res.msg);
		        }
		});

	},
	showSeeHai : function(userId) {
		//$("#userModal").modal('hide');
		Temp.toJid=userId;
		Temp.toUserId=userId;
		$("#divSeeHai #seeText").val("你好,我是"+myData.nickname);
		$("#divSeeHai").modal('show');
	},
	showReplySeeHai : function(userId) {
		Temp.toJid=userId;
		Temp.toUserId=userId;
		$("#divReplySeeHai #replyText").val("你是？");
		$("#divReplySeeHai").modal('show');
	},
	quit : function() {
		window.wxc.xcConfirm("是否确认退出登录？", window.wxc.xcConfirm.typeEnum.confirm,{
			onOk:function(){
				WEBIM.disconnect();
                DataUtils.setLogoutTime(WEBIM.getTimeSecond());
				$.cookie("telephone", "");
				$.cookie("password", "");
				$.cookie("loginData", "");
				window.location.href = "login.html";
			}
		});

	},
	hideChatBodyAndDetails:function(){
		//隐藏右侧界面  聊天界面 和好友详情界面
		ConversationManager.isOpen=false;
		ConversationManager.isGroup=0;
		ConversationManager.from="";
		$("#tabCon_2").hide();
		$("#tabCon_1").hide();
		$("#tabCon_0").hide();
		$("#tabCon_new").hide();
		$("#tab").hide();

	},
	/* 开关切换*/
	switchToggle:function(id,isOpen){
		if(isOpen==1){ //开启
			//$("input[type=checkbox][id='"+id+"']").attr("checked",'checked');
			$("#"+id+"").prop('checked',true);
		}else{
			//$("input[type=checkbox][id='"+id+"']").removeAttr("checked");
			$("#"+id+"").prop('checked',false);
		}
		layui.form.render('checkbox');
	},
	removeFriendMessagesList(userId){
		$("#myMessagesList #friends_"+toUserId).remove();
	},
	removeGroupMessagesList(jid){
		$("#myMessagesList #groups_"+jid).remove();
	},
	sendCard : function(){ //发送名片
		Checkbox.cheackedFriends = {};  //清空储存的数据
		Temp.friendListType="sendCard";
		UI.loadFriendList(0);
	},
	//获取标签的坐标
    getElementPos : function(elementId){
        var ua = navigator.userAgent.toLowerCase();
        var isOpera = (ua.indexOf('opera') != -1);
        var isIE = (ua.indexOf('msie') != -1 && !isOpera); // not opera spoof

        var el = document.getElementById(elementId);

        if (el.parentNode === null || el.style.display == 'none') {
            return false;
        }

        var parent = null;
        var pos = [];
        var box;
        if (el.getBoundingClientRect){ //IE
            box = el.getBoundingClientRect();
            var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
            var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
            return {
                x: box.left + scrollLeft,
                y: box.top + scrollTop
            };
        }else if (document.getBoxObjectFor) {    // gecko

                box = document.getBoxObjectFor(el);
                var borderLeft = (el.style.borderLeftWidth) ? parseInt(el.style.borderLeftWidth) : 0;
                var borderTop = (el.style.borderTopWidth) ? parseInt(el.style.borderTopWidth) : 0;
                pos = [box.x - borderLeft, box.y - borderTop];
        }else{    // safari & opera
                pos = [el.offsetLeft, el.offsetTop];
                parent = el.offsetParent;
                if (parent != el) {
                    while (parent) {
                        pos[0] += parent.offsetLeft;
                        pos[1] += parent.offsetTop;
                        parent = parent.offsetParent;
                    }
                }
                if (ua.indexOf('opera') != -1 || (ua.indexOf('safari') != -1 && el.style.position == 'absolute')) {

                    pos[0] -= document.body.offsetLeft;
                    pos[1] -= document.body.offsetTop;
                }
            }

        if (el.parentNode) {
            parent = el.parentNode;
        }else {
            parent = null;
        }

        while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') { // account for any scrolled ancestors

            pos[0] -= parent.scrollLeft;
            pos[1] -= parent.scrollTop;

            if (parent.parentNode) {
                parent = parent.parentNode;
            }else {
                parent = null;
            }

        }

        return {
            x: pos[0],
            y: pos[1]
        };

    } ,
    scrollToBottomUnread : function(){
    	//让滚动条移动到消息位置
		$("#bottomUnreadCount").remove();
		$(".nano").nanoScroller({ scrollTo: $('.message_system') });
    },

};
